package cog.support.util.common;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * 配置文件加载
 * @version v1.0
 * @author 陈杰
 * */
public class ConfigLoader {
	protected final static Logger logger = LoggerFactory.getLogger(ConfigLoader.class);

	private static Map<String, String> map;

	private static Map<String, String> testMap;

	/**
	 * 加载ClassPath下面的所有配置文件
	 *
	 * @param resources
	 */
	@SuppressWarnings("deprecation")
	public static void init(String resources) {
		logger.debug("<系统信息> 加载配置文件中({})...",resources);
		map = new HashMap<String, String>();
		testMap = new HashMap<String, String>();
		String classpath = ConfigLoader.class.getClassLoader().getResource(resources).getFile();
		String s = URLDecoder.decode(classpath);
		if (!resources.trim().isEmpty()) {
			final String resource = resources;
			File[] propertiesFiles = new File(s).listFiles(new FileFilter() {
				public boolean accept(File pathname) {
					return Pattern.compile(resource).matcher(pathname.getName()).matches();
				}
			});
			for (File file : propertiesFiles) {
				String fileName = file.getAbsolutePath();
				String name = file.getName().substring(0, file.getName().indexOf("."));
				if (fileName.endsWith("-test.properties")) continue;
				Properties prop = new Properties();
				InputStream is;
				try {
					is = new FileInputStream(fileName);
					prop.load(is);
					logger.debug("<系统信息> FileName : {}",fileName);
				} catch (FileNotFoundException e) {
				} catch (IOException e) {
				}
				Set<Object> keys = prop.keySet();
				for (Object key : keys) {
					logger.debug(name+":[" + key + "=" + prop.getProperty(key + "", "") + "]");
					map.put(key.toString(), prop.getProperty(key.toString(),""));
				}

				String testFileName = fileName.substring(0, fileName.indexOf(".properties"))+ "-test.properties";

				Properties tprop = new Properties();
				try {
					InputStream tis = new FileInputStream(testFileName);
					tprop.load(tis);
					logger.debug("<系统信息> testFileName : {}",testFileName);
				} catch (FileNotFoundException e) {
					continue;
				} catch (IOException e) {
					continue;
				}
				Set<Object> tkeys = prop.keySet();
				for (Object tkey : tkeys) {
					String value = tprop.getProperty(tkey.toString(),"");
					if(StringUtils.isNotEmpty(value)){
						logger.debug("{}:[{}={}]",name,tkey,value);
						testMap.put(tkey.toString(),value);
					}
				}
			}
		}
		logger.debug("<系统信息> 配置文件加载结束\n");
	}

	public static Map<String,String> initPropertisFile(String filePath) throws Exception{
		String classpath = ConfigLoader.class.getClassLoader().getResource("").getFile();
		String fullFilePath = filePath.replaceFirst("classpath:",URLDecoder.decode(classpath,"utf-8"));
		Properties prop = new Properties();
		InputStream is = new FileInputStream(fullFilePath);
		prop.load(is);
		logger.debug("<系统信息> 读取配置文件{}",fullFilePath);
		Map<String,String> propertiesMap = new HashMap<String,String>();
		Set<Object> keysSet = prop.keySet();
		for(Object key : keysSet){
			String value = prop.getProperty(key.toString(),"");
			if(!value.equals("") && value.length()>0){
				propertiesMap.put(key.toString(), value);
			}
		}
		logger.debug("<系统信息> 加载配置文件{}完毕，共计加载{}项",filePath,propertiesMap.size());
		return propertiesMap;
	}


	public static String getStr(String key) {
		return getStr(key,null);
	}
	public static String getStr(String key,String defaultValue) {
		if (testMap == null || map == null) {
			throw new RuntimeException("the ConfigPlugin dident start");
		}
		Object val = testMap.get(key);
		if (val==null || "".equals(val)) {
			val = map.get(key);
		}
		return val == null ? defaultValue : val.toString();
	}

	public static long getLong(String key) {
		return getLong(key,0L);
	}
	public static long getLong(String key,long defaultValue) {
		String val = getStr(key);
		if ("".equals(val.trim())) {
			val = null;
		}
		return val==null?defaultValue:Long.parseLong(val);
	}

	public static boolean getBoolean(String key) {
		return getStr(key,"").equals("true");
	}

	public static int getInt(String key) {
		return getInt(key,0);
	}
	public static int getInt(String key,int defaultValue) {
		String val = getStr(key);
		if (val==null || "".equals(val.trim())) {
			val = null;
		}
		return val==null?defaultValue:Integer.parseInt(val);
	}
}